package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Product;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.IProductService;

public class ProductsWaitForPurchaseAdapter extends ArrayAdapter<Product> {
    private List<Product> cartItems = new ArrayList<>(); // 用来存储购物车中的商品
    private IProductService productService;
    private List<Product> productList;
    private SharedPreferences dealerFeedbackPreferences;

    public ProductsWaitForPurchaseAdapter(@NonNull Context context, @NonNull List<Product> products, IProductService productService) {
        super(context, 0, products);
        this.productService = productService;
        this.productList = products;

        // 初始化 SharedPreferences
        dealerFeedbackPreferences = context.getSharedPreferences("ProductFeedback", Context.MODE_PRIVATE);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_product_procurement, parent, false);
        }

        Product product = getItem(position);

        if (product == null || cartItems.contains(product)) {
            // 如果商品已经添加到购物车中，则不显示在页面中
            return convertView;
        }

        // 获取视图中的控件
        TextView productName = convertView.findViewById(R.id.product_name);
        ImageView productImage = convertView.findViewById(R.id.product_image);
        TextView productDetails = convertView.findViewById(R.id.product_details);
        TextView purchaseLink = convertView.findViewById(R.id.purchaseLink);
        TextView feedbackLink = convertView.findViewById(R.id.feedbackLink);

        // 设置产品名称
        productName.setText(product.getProductName());

        // 加载产品图片
        if (product.getImage() != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(product.getImage(), 0, product.getImage().length);
            productImage.setImageBitmap(bitmap);
        } else {
            productImage.setImageResource(R.drawable.default_image);
        }

        // 设置产品详细信息
        String details = String.format("ID: %s\n分类: %s\n生产日期：%s\n价格: %.2f\n",
                product.getProductId(),
                product.getCategory(),
                product.getProduceDate(),
                product.getPrice());

        // 为产品详情设置点击事件，弹出对话框
        productDetails.setOnClickListener(v -> showProductDetailsDialog(product, details));

        // 设置购买链接的点击事件，将商品添加到购物车
        purchaseLink.setOnClickListener(v -> {
            // 添加商品到购物车
            cartItems.add(product);
            productList.remove(product); // 从屏幕上移除该商品
            updateCartCount();
            notifyDataSetChanged(); // 更新视图，使商品消失
        });

        // 设置反馈链接的点击事件，存储产品信息并增加反馈次数
        feedbackLink.setOnClickListener(v -> {
            // 存储反馈信息
            storeFeedback(product);
        });

        updateCartCount();
        return convertView;
    }

    // 存储反馈信息并增加反馈次数
    private void storeFeedback(Product product) {
        SharedPreferences.Editor editor = dealerFeedbackPreferences.edit();

        // 获取当前反馈次数
        int feedbackCount = dealerFeedbackPreferences.getInt(product.getProductId(), 0);
        feedbackCount++; // 增加反馈次数

        // 存储新的反馈次数
        editor.putInt(product.getProductId(), feedbackCount);
        editor.putString(product.getProductId() + "_name", product.getProductName()); // 存储产品名称
        editor.apply();
    }

    // 更新购物车商品数量
    private void updateCartCount() {
        ImageView cartIcon = ((Activity) getContext()).findViewById(R.id.cart_icon);
        TextView cartCount = ((Activity) getContext()).findViewById(R.id.cart_count);

        int itemCount = cartItems.size();
        cartCount.setText(String.valueOf(itemCount));

        if (itemCount == 0) {
            cartCount.setVisibility(View.GONE);
        } else {
            cartCount.setVisibility(View.VISIBLE);
        }

        cartIcon.setOnClickListener(v -> showCartDialog());
    }

    // 显示购物车的支付弹窗
    private void showCartDialog() {
        StringBuilder cartDetails = new StringBuilder();
        double totalPrice = 0.0;

        for (Product product : cartItems) {
            cartDetails.append(String.format("商品名称: %s - 价格: %.2f", product.getProductName(), product.getPrice()));
            cartDetails.append("\n");
            totalPrice += product.getPrice();
        }

        cartDetails.append("\n总价: ").append(totalPrice);

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("购物车")
                .setMessage(cartDetails.toString())
                .setPositiveButton("确认支付", (dialog, which) -> {
                    productService.purchaseByDealerInBulk(cartItems.stream().map(Product::getProductId).toArray(String[]::new));

                    for (Product product : cartItems) {
                        productList.remove(product); // 从产品列表中移除已购买的商品
                    }

                    cartItems.clear();
                    updateCartCount();

                    notifyDataSetChanged(); // 更新视图
                    Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // 取消支付时，将购物车中的商品恢复回产品列表
                    productList.addAll(cartItems);
                    cartItems.clear();
                    updateCartCount();
                    notifyDataSetChanged(); // 更新视图，使被删除的商品恢复
                })
                .show();
    }

    private void showProductDetailsDialog(Product product, String details) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("产品详细信息");
        builder.setMessage(details);
        builder.setPositiveButton("确定", null);
        builder.show();
    }
}






